package service

import (
	"github.com/gin-gonic/gin"
	"gochat/common"
	"gochat/domain/request"
	"gochat/domain/response/result"
	"gochat/models"
	"gorm.io/gorm"
	"log"
	"strconv"
)

type GroupServiceImpl struct {
}

func (group GroupServiceImpl) CreateGroup(c *gin.Context, body request.CreateGroupRequest) {
	id, err := strconv.ParseUint(c.GetString("uid"), 10, 64)
	if err != nil {
		log.Println(err)
		result.Fail(c, 500, "服务器未知异常")
		return
	}
	uid := uint(id)
	db := common.DB
	err = db.Transaction(func(tx *gorm.DB) error {
		groupModel := models.GroupModel{
			GroupName:   body.GroupName,
			GroupHeader: "",
			CreateBy:    int(uid),
		}
		rtx := tx.Save(&groupModel)
		if rtx.Error != nil {
			return rtx.Error
		}
		var userGroup []models.UserGroup
		userGroup = append(userGroup, models.UserGroup{
			UserId:  uid,
			GroupId: groupModel.ID,
		})
		//	todo 发送群邀请给其他用户

		//for i := range body.Users {
		//	userGroup = append(userGroup, models.UserGroup{
		//		UserId:  body.Users[i],
		//		GroupId: groupModel.ID,
		//	})
		//	err := queueBind("queuename."+strconv.Itoa(int(body.Users[i])), "group."+strconv.Itoa(int(groupModel.ID)),
		//		"message.group")
		//	if err != nil {
		//		return err
		//	}
		//}
		rtx = tx.Create(&userGroup)
		if rtx.Error != nil {
			return rtx.Error
		}
		return nil
	})
	if err != nil {
		log.Println(err)
		result.Fail(c, 500, "创建群组失败")
		return
	}
	result.Ok(c, "创建群组成功")

}

// GroupList 根据用户id获取群组列表
func (group GroupServiceImpl) GroupList(c *gin.Context, uid int64) {
	db := common.DB
	var groups []models.GroupModel
	err := db.Joins("JOIN user_groups ug ON ug.group_id = groups.id").
		Where("ug.user_id = ?", uid).
		Find(&groups).Error
	if err != nil {
		log.Println(err)
		result.Fail(c, 500, "获取群组列表失败")
		return
	}
	result.Ok(c, groups)

}
func UnQueueBind(queue string, routingKey string, exchange string) error {
	connection, err := common.RabbitPools.GetConnection()
	if err != nil {
		return err
	}
	channel, err := connection.Channel()
	if err != nil {
		return err
	}
	err = channel.QueueUnbind(queue, routingKey, exchange, nil)
	if err != nil {
		return err
	}
	return nil
}
func queueBind(queue string, routingKey string, exchange string) error {

	connection, err := common.RabbitPools.GetConnection()
	if err != nil {
		return err
	}
	channel, err := connection.Channel()
	if err != nil {
		return err
	}
	_, err = channel.QueueDeclare(
		queue, // 队列名
		true,  // durable，持久化队列，RabbitMQ 重启后依然存在
		false, // autoDelete，是否自动删除
		false, // exclusive，是否排他队列
		false, // noWait，是否异步
		nil,   // arguments，额外参数
	)
	if err != nil {
		// 处理错误
		return err
	}

	err = channel.QueueBind(queue, routingKey, exchange, false, nil)
	if err != nil {
		return err
	}
	defer channel.Close()

	return nil
}
